package de.gwtprime.client.views.popup;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.event.UserSettingsChangedEvent;
import de.gwtprime.shared.requestFactory.User2Proxy;
import de.gwtprime.shared.requestFactory.request.User2Request;

public class ChangeUserSettingsPopup extends Composite{

	ChangeUserSettingsPopupUiBinder uiBinder = GWT.create(ChangeUserSettingsPopupUiBinder.class);
	interface ChangeUserSettingsPopupUiBinder extends UiBinder<Widget, ChangeUserSettingsPopup>{}

	
	private ClientFactory clientFactory;
	
	@UiField TextBox userNameTextbox;
	
	@UiField Button saveChangesButton;
	
	public ChangeUserSettingsPopup(ClientFactory clientFactory){
		initWidget(uiBinder.createAndBindUi(this));
		this.clientFactory = clientFactory;
		
		userNameTextbox.setText(clientFactory.getUser().getName());
	}
	
	@UiHandler("saveChangesButton")
	public void onSaveChanges(ClickEvent e){
		
		User2Request userRequest = clientFactory.getRequestFactory().userRequest();
		
		
		final User2Proxy user = userRequest.edit(clientFactory.getUser());;
		
		
		user.setName(userNameTextbox.getText());
		//((PopupPanel)ChangeUserSettingsPopup.this.getParent()).hide(true);
		
		userRequest.persist().using(user).fire(new Receiver<Long>() {
			@Override
			public void onSuccess(Long response) {

				clientFactory.getEventBus().fireEvent(new UserSettingsChangedEvent(user));
				clientFactory.setUser(user);
				
			}
		});
		
		
		
		
	}

}
